//
//  ForumDetailVC.m
//  Project2
//
//  Created by hundredsandc on 2017/11/7.
//  Copyright © 2017年 hundredsandc. All rights reserved.
//

#import "ForumDetailVC.h"
#import "customTextField.h"
#import "AllCommentTableViewCell.h"
#import "login.h"
@interface ForumDetailVC ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>
@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)UIView *underView;
@property (nonatomic,strong)customTextField *editTF;
@property (nonatomic,strong)NSMutableArray *dataArr;
@property(strong,nonatomic)UIScrollView     *scrollView;
@property(nonatomic,strong)NSDictionary     *detailDict;
@property (nonatomic,strong)UIImageView *likeImageV;
@end

@implementation ForumDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"帖子详情";
    
    [self getDetailData];
    [self getCommentData];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignTF)];
    [self.view addGestureRecognizer:tap];
   
}
-(void)resignTF{
    [_editTF resignFirstResponder];
    
}
-(void)setupUI{
    [self.view addSubview:self.tableView];
    [self addUnderView];
}
- (void)getDetailData
{
    NSString *url =[NSString stringWithFormat:@"%ld",self.model.Id];
    [SVProgressHUD showWithStatus:@"请求中..."];
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    param[@"split"] = @"on";
    NSString *aBBSDetailsUrl = [NSString stringWithFormat:@"api/topic/%@",url];
    
    NSLog(@"参数:%@",url);
    [HTTPManagers postBBSWithURL:aBBSDetailsUrl params:param success:^(id json)
     {
         if ([json[@"code"] integerValue] == 0)
         {
             self.detailDict = json[@"message"];
             [self setupUI];
         }else{
             [SVProgressHUD showErrorWithStatus:@"请求失败"];
         }
         [SVProgressHUD dismiss];
         
     } failure:^(NSError *error)
     {
         NSLog(@"%@",error);
         [SVProgressHUD showErrorWithStatus:@"请检查网络"];
     }];
}
-(void)getCommentData{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"tid"] = @(self.model.Id);
    params[@"alive"] = @"off";
    [HTTPManagers postCommentWithURL:@"comment" params:params success:^(id json) {
        
        self.dataArr = [json objectForKey:@"message"];
        [_tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}
-(void)addUnderView{
        UILabel *zan = [UIManage createUILabelFrame:CGRectMake(SCREEN_WIDTH/2, _tableView.bottom, 50, 50) withBackColor:nil withTextColor:RGBCOLOR(0x33, 0x33, 0x33) withTextFont:FONT(12) withTextAlignment:NSTextAlignmentCenter withTextContent:@"赞一个"];
        [self.view addSubview:zan];
    
        UIButton *btnLike=[UIButton buttonWithType:UIButtonTypeCustom];
        btnLike.frame=RectMake(SCREEN_WIDTH/2-50, zan.y, 50 , 50);
    
        [btnLike addTarget:self action:@selector(likeClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _likeImageV = [[UIImageView alloc]init];
        _likeImageV.image = [UIImage imageNamed:@"post_pra2"];
        _likeImageV.contentMode = UIViewContentModeScaleAspectFit;
        [btnLike addSubview:_likeImageV];
        [self.view addSubview:btnLike];
    [_likeImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(btnLike);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];

    
    _underView = [[UIView alloc]initWithFrame:CGRectMake(0, _tableView.bottom+50, SCREEN_WIDTH, FTab)];
    
    _editTF = [[customTextField alloc]initWithFrame:CGRectMake(20, 10, SCREEN_WIDTH-60-40, 29) leftImagePath:@"bianji" PlaceHolder:@"编辑..."];
    [_underView addSubview:_editTF];
    
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    sendBtn.frame = CGRectMake(SCREEN_WIDTH-60, 10, 40, 29);
    [sendBtn setTitle:@"发表" forState:UIControlStateNormal];
    sendBtn.titleLabel.font = FONT(14);
    [sendBtn setTitleColor:RGBCOLOR(0x25, 0x43, 0x7f) forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendAction) forControlEvents:UIControlEventTouchUpInside];
    [_underView addSubview:sendBtn];
    
    [self.view addSubview:_underView];
}
-(void)likeClick:(UIButton *)sender{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"tid"] = self.detailDict[@"Id"];
    [HTTPManagers postLikeWithURL:@"like" params:params success:^(id json) {
        if ([json[@"message"]isEqualToString:@"unrepeatable like"]) {
            [SVProgressHUD showErrorWithStatus:@"您已点过赞～" maskType:SVProgressHUDMaskTypeGradient];
            _likeImageV.image = [UIImage imageNamed:@"post_pra1"];
            
            
            return ;
        }
        if ([json[@"code"]integerValue]==1) {
            [SVProgressHUD showErrorWithStatus:@"当前未登录" maskType:SVProgressHUDMaskTypeGradient];
            login *vc = [login new];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            
            
            
        }
        if ([json[@"code"] intValue] == 0) {
            
            [SVProgressHUD showSuccessWithStatus:@"点赞成功"];
            _likeImageV.image = [UIImage imageNamed:@"post_pra1"];
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}
-(void)sendAction{
    if (_editTF.text.length<5) {
        [SVProgressHUD showErrorWithStatus:@"回复内容(内容长度最低为5)" maskType:SVProgressHUDMaskTypeGradient];
        
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"tid"] = @(self.model.Id);
    params[@"uid"] = @"";
    params[@"content"] = _editTF.text;
    [HTTPManagers postCommentAddWithURL:@"add" params:params success:^(id json) {
        if ([json[@"code"]integerValue]==1) {
             [SVProgressHUD showErrorWithStatus:@"当前未登录" maskType:SVProgressHUDMaskTypeGradient];
            login *vc = [login new];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
             [SVProgressHUD showErrorWithStatus:@"评论成功" maskType:SVProgressHUDMaskTypeGradient];
            _editTF.text = @"";
            [_editTF resignFirstResponder];
            [self getCommentData];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }else{
        if (self.dataArr!=nil &&self.dataArr!=[NSNull null]) {
            return self.dataArr.count;
        }
        return 0;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 30;
    }
    return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *foot = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    foot.backgroundColor = [UIColor whiteColor];
    UILabel *like = [UIManage createUILabelFrame:CGRectMake(15, 0, 50, 24) withBackColor:nil withTextColor:RGBCOLOR(0x66, 0x66, 0x66) withTextFont:FONT(12) withTextAlignment:NSTextAlignmentLeft withTextContent:[NSString stringWithFormat:@"%ld 喜欢",self.model.Like]];
    [foot addSubview:like];
    
    UILabel *comment = [UIManage createUILabelFrame:CGRectMake(like.right+35, 0, 50, 24) withBackColor:nil withTextColor:RGBCOLOR(0x66, 0x66, 0x66) withTextFont:FONT(12) withTextAlignment:NSTextAlignmentLeft withTextContent:[NSString stringWithFormat:@"%ld 回复",self.model.CommentCount]];
    [foot addSubview:comment];
    UIView *under = [[UIView alloc]initWithFrame:CGRectMake(0, 24, SCREEN_WIDTH, 6)];
    under.backgroundColor = RGBCOLOR(0xf4, 0xf4, 0xf4);
    [foot addSubview:under];
    
    return foot;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        
        return 350;
    }else{
        return 80;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        self.scrollView=[[UIScrollView alloc]initWithFrame:RectMake(0, 0, SCREEN_WIDTH, 350)];
        [cell.contentView addSubview:self.scrollView];
        
        UILabel *lableTitle=[[UILabel alloc]initWithFrame:RectMake(10, 0, SCREEN_WIDTH-20, 70)];
        NSString *titleStr = [self.model.Title stringByReplacingOccurrencesOfString:@" " withString:@""];
        titleStr = [titleStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        lableTitle.text=titleStr;
        lableTitle.textColor=HWColor(102, 102, 102);
        lableTitle.textAlignment=NSTextAlignmentCenter;
        lableTitle.font=[UIFont systemFontOfSize:16];
        lableTitle.numberOfLines = 2;
        
        [self.scrollView addSubview:lableTitle];
        
        
        
        SDCycleScrollView *headerCycleView =[SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(20, 70, (SCREEN_WIDTH-40), 117) delegate:self placeholderImage:nil];
        headerCycleView.localizationImageNamesGroup = @[@"banner1",@"banner2-",@"banner3"];
        headerCycleView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        headerCycleView.pageDotColor = [UIColor lightGrayColor];
        headerCycleView.autoScrollTimeInterval = 2.0;
        [self.scrollView addSubview:headerCycleView];
        
        UITextView *textView=[[UITextView alloc]init];
        textView.font=[UIFont systemFontOfSize:14];
        textView.text=[[self.detailDict valueForKey:@"Content"]valueForKey:@"Content"];
        textView.editable=NO;
        
        CGFloat textY;
        textY=[self getLabelHeightWithString:textView.text andWidth:SCREEN_WIDTH-10 andFont:[UIFont systemFontOfSize:14]];
        
        self.scrollView.contentSize=CGSizeMake(SCREEN_WIDTH,textY+187+10+100 );
        textView.frame=RectMake(10, 187+10, SCREEN_WIDTH-10, textY+100);
        
        
        textView.textColor=[UIColor blackColor];
        [self.scrollView addSubview:textView];

       
        return cell;
    }else{
    AllCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AllCommentTableViewCell class]) forIndexPath:indexPath];
    
    if (self.dataArr.count>0) {
        NSDictionary *dict = self.dataArr[indexPath.row];
        NSInteger timeSp = [dict[@"Creation"]integerValue];
        NSString *time = [YXComUtil changeTimeToTimeStr:timeSp formate:@"yyyy.MM.dd"];
        [cell customName:dict[@"UserName"] time:time content:dict[@"Content"]];
    }
        return cell;
    }
    
    
}
//获取高度,传入文本框的宽度和字号以及内容
-(CGFloat)getLabelHeightWithString:(NSString *)text andWidth:(CGFloat)width andFont:(UIFont *)font{
    UITextView* textViewTemple = [[UITextView alloc]init];
    textViewTemple.text = text;
    //    [textViewTemple setFont:[UIFont systemFontOfSize:14]];
    [textViewTemple setFont:font];
    //     获取该段attributedString的属性字典
    CGSize textSize = [textViewTemple.text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) // 用于计算文本绘制时占据的矩形块
                                                        options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                                     attributes:[NSDictionary dictionaryWithObjectsAndKeys:textViewTemple.font,NSFontAttributeName, nil]         // 文字的属性
                                                        context:nil].size;
    return textSize.height;
}
-(NSString *)changeTimeStr2Date:(NSString *)string{
    NSTimeInterval time=[string doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-FTab-50) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([AllCommentTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([AllCommentTableViewCell class])];
       
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

@end
